/*
 * @Author: 杨光辉(GerhardYang)
 * @Date: 2021-06-01 11:10:42
 * @LastEditors: 予程_hepch
 * @LastEditTime: 2022-03-25 16:32:42
 * @Description: file content
 * @Copyright: 超图软件华中平台客户中心 (SuperMap Software Co., Ltd. -Central China Platform)
 */
import axios from "axios";
import L from "leaflet";
import {
  queryService,
  FilterParameter,
  QueryByDistanceParameters,
  QueryByGeometryParameters,
  featureService,
  GetFeaturesBySQLParameters,
  layerInfoService,
  GetFeaturesByGeometryParameters,
} from "@supermap/iclient-leaflet";

/**
 * @description:
 * @param {array} datasetNames ["数据源:数据集"]
 * @param {string} sql 查询过滤条件
 * @return {getFeaturesByGeometryParameters} 几何查询查询
 */
const dataGetFeaturesByGeometryParameters = (
  datasetNames,
  sql,
  geometry,
  arrayfileds,
  queryNum,
  fromIndex,
  toIndex
) => {
  return new GetFeaturesByGeometryParameters({
    geometry: geometry,
    attributeFilter: sql,
    spatialQueryMode: "CONTAIN",
    returnContent: true,
    targetEpsgCode: 4326,
    datasetNames: datasetNames,
    fromIndex: fromIndex || 0,
    toIndex: toIndex || 200,
    maxFeatures: queryNum || 200,
    fields: arrayfileds || null,
  });
};
/**
 * @description: 几何查询
 * @param {string} dataUrl 数据服务URL
 * @param {GetFeaturesByGeometryParameters} geometryParam 参数参数
 * @return {reslut} 查询结果
 */
const dataGetFeaturesByGeometry = (dataUrl, geometryParam) => {
  return new Promise((resolve) => {
    L.supermap
      .featureService(dataUrl)
      .getFeaturesByGeometry(geometryParam, (serviceResult) => {
        let result = serviceResult.result;
        console.log(`${dataUrl}查询结果result:`, result);
        resolve(result);
      });
  });
};
/**
 * @description: 获取可查询图层
 * @param {string}mapUrl SuperMap地图URL
 * @return {array}可查询子图层名称数组
 */
const getQueryLayers = (mapUrl) => {
  return new Promise((resolve, reject) => {
    axios.get(mapUrl + "/layers.json").then((res) => {
      let queryableLayers = [];
      res.data[0].subLayers.layers.map((layer) => {
        // if (layer.queryable) {
        queryableLayers.push(layer.name);
      });
      if (res.data[0].subLayers.layers) {
        console.log(
          `${mapUrl.split("/").pop()},可查询图层获取成功`,
          queryableLayers
        );
      } else {
        console.log(`${mapUrl.split("/").pop()},可查询图层获取错误！`);
      }
      resolve(queryableLayers);
      reject();
    });
  });
};

/**
 * @description: SuperMap空间查询
 * @param {Object} param 空间查询参数
 * @param {string} layerType 空间查询类型 点、线、面
 * @param {string} mapUrl 地图URL
 * @return {Object} 空间查询结果记录集recordsets
 */
const smSpatialQuery = (param, layerType, mapUrl) => {
  const promise = new Promise((resolve) => {
    if (layerType == "circlemarker" || layerType == "circle") {
      queryService(mapUrl).queryByDistance(param, (serviceResult) => {
        let recordsets = serviceResult.result.recordsets;
        console.log(
          `${mapUrl.split("/").pop()}查询结果recordsets:`,
          recordsets
        );
        resolve(recordsets);
      });
    } else {
      queryService(mapUrl).queryByGeometry(param, (serviceResult) => {
        let recordsets = serviceResult.result.recordsets;
        console.log(
          `${mapUrl.split("/").pop()}查询结果recordsets:`,
          recordsets
        );
        resolve(recordsets);
      });
    }
  });
  return promise;
};

/**
 * @description: 根据URL添加地图到指定图层组
 * @param {LayerGroup} LayerGroup 图层组
 * @param {object} dataref tree节点dataref
 * @return {string} 图层ID
 */
const addSmThemeLayer = (LayerGroup, dataref) => {
  let cartoCSS = null;
  let style_flag = true;
  let nodeLayerId = null;
  let vectorLayer = null;

  //   let themeMap = L.supermap
  //   .tiledMapLayer(dataref.mapUrl, { noWrap: true, maxZoom: 21 })
  //   .addTo(LayerGroup)
  //   .setZIndex(4);
  // nodeLayerId = LayerGroup.getLayerId(themeMap);
  // return nodeLayerId;
  if (dataref.vectortype === "REGION") {
    let themeMap = L.supermap
      .tiledMapLayer(dataref.mapUrl, { noWrap: true, maxZoom: 21 })
      .addTo(LayerGroup)
      .setZIndex(4);
    nodeLayerId = LayerGroup.getLayerId(themeMap);
    return nodeLayerId;
  } else if (dataref.vectortype === "LINE") {
    style_flag = true;
    vectorLayer = L.supermap
      .tiledVectorLayer(dataref.mapUrl, {
        timeout: 10000000,
        cacheEnabled: true,
        returnAttributes: true,
        serverCartoCSSStyle: style_flag,
      })
      .addTo(LayerGroup)
      .setZIndex(4);

    nodeLayerId = LayerGroup.getLayerId(vectorLayer);
    console.log(
      `图层:[${dataref.title}]添加成功,图层ID为:${nodeLayerId}`,
      vectorLayer.getDataLayerNames()
    );
    return nodeLayerId;
  } else {
    style_flag = false;
    // let style_url =
    //   dataref.mapUrl +
    //   "/tileFeature/vectorstyles.rjson?type=cartoCSS&layerNames=";
    // axios.get(style_url, {}).then((resp) => {cartoCSS = resp.data.style;})
    vectorLayer = L.supermap
      .tiledVectorLayer(dataref.mapUrl, {
        timeout: 10000000,
        cacheEnabled: true,
        returnAttributes: true,
        serverCartoCSSStyle: style_flag,
        cartoCSS: cartoCSS,
        //processCharacters:true,
      })
      .addTo(LayerGroup)
      .setZIndex(4);
    nodeLayerId = LayerGroup.getLayerId(vectorLayer);
    console.log(`图层:[${dataref.title}]添加成功,图层ID为:${nodeLayerId}`);
    return nodeLayerId;
  }
};

const addTileSmThemeLayer = (LayerGroup, dataref) => {
  console.log("地图信息", dataref);
  let vectorLayer = null;

  vectorLayer = L.supermap
    .tiledMapLayer(dataref.mapUrl, {
      minZoom: dataref.minzoom,
      maxZoom: dataref.maxzoom,
      bounds: [
        [24.62, 108.783],
        [30.13, 114.25],
      ],
    })
    .addTo(LayerGroup)
    .setZIndex(5);
  let nodeLayerId = LayerGroup.getLayerId(vectorLayer);
  console.log(`图层:[${dataref.title}]添加成功,图层ID为:${nodeLayerId}`);
  return nodeLayerId;
};
const getLayersInfo = (dataref) => {
  let vectorinfo = null;
  return new Promise((resove) => {
    if (dataref.mapUrl && dataref.mapUrl !== "") {
      layerInfoService(dataref.mapUrl).getLayersInfo(function (serverResult) {
        if (serverResult.type === "processFailed") {
          resove(vectorinfo);
        } else {
          let layers = serverResult.result.subLayers.layers;
          vectorinfo = layers;
          vectorinfo.mapname = serverResult.result.name;
          resove(vectorinfo);
        }
      });
    } else {
      resove(vectorinfo);
    }
  });
};
/**
 * @description: 构建地图查询参数
 * @param {array} queryableLayers 可查询子图层数组
 * @param {object} event 绘制完成事件可获取到绘制的图形和类型
 * @param {string} SQL 查询
 * @return {object} SM空间查询参数
 */
const setQueryPermeterGeometry = (
  queryableLayers,
  event,
  sql,
  backFileds,
  bufferGeometry
) => {
  let param;
  let queryParams = [];
  for (let layer of queryableLayers) {
    let queryParam = new FilterParameter({
      name: layer,
      attributeFilter: sql ? sql : "SMID > 0",
      fields: backFileds ? backFileds : null,
    });
    queryParams.push(queryParam);
  }
  var geometry = L.Util.transform(event.layer, L.CRS.EPSG4326, L.CRS.EPSG3857);
  if (event.layerType == "circle") {
    param = new QueryByDistanceParameters({
      queryParams: queryParams,
      distance: event.layer._mRadius ? event.layer._mRadius : 5,
      geometry: geometry,
    });
  } else if (event.layerType == "circlemarker") {
    param = new QueryByDistanceParameters({
      queryParams: queryParams,
      distance: event.layer._mRadius ? event.layer._mRadius : 200,
      geometry: geometry,
      expectCount: 1,
      //isNearest: true,
    });
  } else if (event.layerType == "polyline") {
    param = new QueryByGeometryParameters({
      queryParams: queryParams,
      geometry: L.Util.transform(
        bufferGeometry,
        L.CRS.EPSG4326,
        L.CRS.EPSG3857
      ),
    });
  } else {
    param = new QueryByGeometryParameters({
      queryParams: queryParams,
      geometry: geometry,
    });
  }
  return param;
};

/**
 * @description:
 * @param {array} datasetNames ["数据源:数据集"]
 * @param {string} sql 查询过滤条件
 * @return {GetFeaturesBySQLParameters} SQL查询查询
 */
const dataGetFeaturesBySQLParameters = (
  datasetNames,
  sql,
  arrayfileds,
  queryNum
) => {
  return new GetFeaturesBySQLParameters({
    queryParameter: {
      attributeFilter: sql,
      fields: arrayfileds || null,
      //orderBy: "NAME ASC", //DESC  ASC
    },
    returnContent: true,
    targetEpsgCode: 4326,
    datasetNames: datasetNames,
    toIndex: queryNum || 200,
    maxFeatures: queryNum || 200,
  });
};
/**
 * @description:
 * @param {array} datasetNames ["数据源:数据集"]
 * @param {string} sql 查询过滤条件
 * @return {GetFeaturesBySQLParameters} SQL查询查询
 */
const dataGetRoadBySQLParameters = (
  datasetNames,
  sql,
  arrayfileds,
  queryNum
) => {
  return new GetFeaturesBySQLParameters({
    queryParameter: {
      attributeFilter: sql,
      fields: arrayfileds || null,
    },
    returnContent: true,
    targetEpsgCode: 4326,
    datasetNames: datasetNames,
    toIndex: queryNum || 10,
    maxFeatures: queryNum || 10,
  });
};

/**
 * @description: SQL查询
 * @param {string} dataUrl 数据服务URL
 * @param {GetFeaturesBySQLParameters} param 参数参数
 * @return {reslut} 查询结果
 */
const dataGetFeaturesBySQL = (dataUrl, param) => {
  return new Promise((resolve) => {
    featureService(dataUrl).getFeaturesBySQL(param, (serviceResult) => {
      let result = serviceResult.result;
      console.log(`${dataUrl}查询结果result:`, result);
      resolve(result);
    });
  });
};

export {
  getQueryLayers,
  smSpatialQuery,
  addSmThemeLayer,
  addTileSmThemeLayer,
  setQueryPermeterGeometry,
  dataGetFeaturesBySQLParameters,
  dataGetFeaturesBySQL,
  dataGetFeaturesByGeometryParameters,
  dataGetFeaturesByGeometry,
  dataGetRoadBySQLParameters,
  getLayersInfo,
};
